package com.mf.basic.services;

import cn.dev33.satoken.stp.StpUtil;
import com.mf.basic.entity.DtoUser;
import com.mf.basic.enums.EnumBaseParams;
import jakarta.annotation.Resource;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Created by Luke on 2025/3/7 17:05.
 */
@Service
public class ServiceLogin {

    @Resource
    private ServiceUser serviceUser;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 登录校验
     * @param username 用户名
     * @param password 密码
     * @return DtoUser
     */
    public DtoUser doCheck(String username, String password) {
        DtoUser user = serviceUser.findByUserName(username);
        Assert.state(user != null,  "用户名或密码错误(1), 请检查");
        Assert.state(passwordEncoder.matches(password, user.getPassword()), "用户名或密码错误(2), 请检查");
        Assert.state(user.getStatus() == 0, "用户已被禁用, 请联系管理员");
        user.setPassword("");
        //执行登录
        StpUtil.login(user.getId());
        //缓存用户
        StpUtil.getSession().set(EnumBaseParams.douser.name(), user.getUsername())
                .set(EnumBaseParams.userId.name(), user.getId());
        user.setTokenValue(StpUtil.getTokenInfo().tokenValue)
                .setPermissions(StpUtil.getPermissionList());
        return user;
    }

}
